<template>
  <div class="updateName">
    <van-nav-bar
      title="修改昵称"
      left-text="取消"
      right-text="完成"
      @click-left="$emit('close')"
      @click-right="onConfirm"
    />

    <div class="name-field-wrap">
      <van-field
        v-model="localName"
        rows="2"
        autosize
        type="textarea"
        maxlength="7"
        placeholder="请输入昵称"
        show-word-limit
      />
    </div>
  </div>
</template>

<script>
import { updateUserProfile } from "../api/user.js";
export default {
  name: "updataName",
  data() {
    return {
      localName: this.value
    };
  },
//   
  props: {
    value: {
      type: String,
      required: true
    }
  },
  methods: {
    async onConfirm() {
      this.$toast.loading({
        message: "保存中",
        forbidclick: true
      });

      // 昵称可能已经存在需要作判断
      try {
        // 提交更新用户昵称
        const { data } = await updateUserProfile({
          name: this.localName
        });
        this.$toast.success("保存成功");
        // 直接让父级更新不用刷新  发布input事件，更新父组件v-model绑定的数据
        this.$emit("input", this.localName);
        // 关闭弹出层
        this.$emit("close");
      } catch (err) {
        if (err && err.response && err.response.status === 409) {
          this.$toast.fail("昵称已存在");
        }
      }
    }
  }
};
</script>
<style scoped lang="less">
.name-field-wrap {
  padding: 10px;
}
</style>
